package com.easymin.weixin.controller.v2;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSONObject;
import com.easymin.weixin.common.CommonUtil;
import com.easymin.weixin.common.DataGrid;
import com.easymin.weixin.common.PhoneNumberHelper;
import com.easymin.weixin.common.api.DaijiaApi;
import com.easymin.weixin.common.api.PassengerApi;
import com.easymin.weixin.common.api.SalesApi;
import com.easymin.weixin.common.api.ZhuanApi;
import com.easymin.weixin.common.api.ZhuanXianApi;
import com.easymin.weixin.common.transport.Error;
import com.easymin.weixin.common.transport.Result;
import com.easymin.weixin.entity.Order;
import com.easymin.weixin.entity.OrderType;
import com.easymin.weixin.entity.WxApplication;
import com.easymin.weixin.entity.passenger.Passenger;
import com.easymin.weixin.entity.sales.Coupon;
import com.easymin.weixin.manager.ErrandManager;
import com.easymin.weixin.manager.FreightManager;
import com.easymin.weixin.manager.WxApplicationManager;
import com.google.common.base.Preconditions;

@RestController
@RequestMapping("api/errand/v2/orders")
public class OrderV2Res {
  
  private static final Logger logger = LoggerFactory.getLogger(OrderV2Res.class);

  @Autowired
  private ErrandManager errandManager;
  @Autowired
  private FreightManager freightManager;
  @Autowired
  private WxApplicationManager wxApplicationManager;
  @Autowired
  private DaijiaApi daijiaApi;
  @Autowired
  private PassengerApi passengerApi;
  @Autowired
  private SalesApi salesApi;
  @Autowired
  private ZhuanApi zhuanApi;
  @Autowired
  private ZhuanXianApi zhuanXianApi;
  

  /**
   * 创建跑腿订单.
   * @param passengerId 客户Id
   * @param passengerName 客户姓名
   * @param passengerPhone 客户电话
   * @param companyId 公司Id
   * @param companyName 公司名字
   * @param channelName 订单来源
   * @param startAddress 起点地址
   * @param startLat 起点地址纬度
   * @param startLng 起点地址经度
   * @param deliverAddress 交付地址
   * @param deliverLat 交付地纬度
   * @param deliverLng 交付地经度
   * @param startTime 预约时间
   * @param startPrice 起步价
   * @param mileagePrice 里程费
   * @param travelTimePrice 时间费
   * @param mileage 预计里程
   * @param travelTime 预计时间
   * @param shouldPay 预估价格
   * @param couponId 优惠券id
   * @param photo1 附件图片1
   * @param photo2 附件图片2
   * @param photo3 附件图片3
   * @param photo4 附件图片4
   * @param photo5 附件图片5
   * @param orderTypeId 跑腿类型id
   * @param content 任务文本
   * @param appKey 区分系统
   * @param recipients 收件人
   * @param phone 收件人电话
   * @param weight 重量
   * @param buyNeeds 购买需求
   * @param goodsCash 商品金额
   * @param thanksCash 感谢费
   * @param addServices 附加服务
   * @param tips 热门标签
   * @param startDetailed 详细开始地点
   * @param endDetailed 详细结束地点
   * @return 跑腿订单
   */
  @ResponseBody
  @RequestMapping(value = {"create"}, method = RequestMethod.POST)
  public ResponseEntity<Object> create(
      @RequestParam("passengerId") Long passengerId,
      @RequestParam("passengerName") String passengerName,
      @RequestParam("passengerPhone") String passengerPhone,
      @RequestParam("companyId") Long companyId,
      @RequestParam("companyName") String companyName,
      @RequestParam("channelName") String channelName, 
      @RequestParam(required = false, value = "startAddress") String startAddress,
      @RequestParam(required = false, value = "startLat") Double startLat,
      @RequestParam(required = false, value = "startLng") Double startLng,
      @RequestParam(required = false, value = "deliverAddress") String deliverAddress,
      @RequestParam(required = false, value = "deliverLat") Double deliverLat,
      @RequestParam(required = false, value = "deliverLng") Double deliverLng, 
      @RequestParam(required = false, value = "startTime") Long startTime,
      @RequestParam(required = false, value = "startPrice") Double startPrice, 
      @RequestParam(required = false, value = "mileagePrice") Double mileagePrice,
      @RequestParam(required = false, value = "travelTimePrice") Double travelTimePrice,
      @RequestParam(required = false, value = "mileage") Double mileage,
      @RequestParam(required = false, value = "travelTime") Integer travelTime, 
      @RequestParam(required = false, value = "shouldPay") Double shouldPay,
      @RequestParam(required = false, value = "orderTypeId") Long orderTypeId,
      @RequestParam(required = false, value = "couponId") Long couponId,
      @RequestParam(required = false, value = "photo1") MultipartFile photo1,
      @RequestParam(required = false, value = "photo2") MultipartFile photo2, 
      @RequestParam(required = false, value = "photo3") MultipartFile photo3,
      @RequestParam(required = false, value = "photo4") MultipartFile photo4,
      @RequestParam(required = false, value = "photo5") MultipartFile photo5,
      @RequestParam(required = false, value = "content") String content, 
      @RequestParam(required = false, value = "startDetailed") String startDetailed,
      @RequestParam(required = false, value = "endDetailed") String endDetailed,
      @RequestParam(required = false, value = "recipients") String recipients,
      @RequestParam(required = false, value = "phone") String phone,
      @RequestParam(required = false, value = "weight") String weight,
      @RequestParam(required = false, value = "matter") String matter,
      @RequestParam(required = false, value = "buyNeeds") String buyNeeds,
      @RequestParam(required = false, value = "goodsCash") Double goodsCash,
      @RequestParam(required = false, value = "thanksCash") Double thanksCash,
      @RequestParam(required = false, value = "addServices") String addServices,
      @RequestParam(required = false, value = "tips") String tips,
      HttpServletRequest req,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    try {
      appKey = StringUtils.trimToEmpty(appKey);
      Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
//      if (StringUtils.isBlank(content)) {
//        Error error = new Error(-1, "参数错误:任务内容为空");
//        responseEntity = new ResponseEntity<Object>(error, HttpStatus.OK);
//        return responseEntity;
//      }
      if (StringUtils.isNotBlank(content) && content.length() > 200) {
        Error error = new Error(-41, "内容长度过长");
        responseEntity = new ResponseEntity<Object>(error, HttpStatus.OK);
        return responseEntity;
      }
      if (null == companyId || StringUtils.isBlank(companyName)) {
        Error error = new Error(-1, "参数错误:公司不能为空");
        responseEntity = new ResponseEntity<Object>(error, HttpStatus.OK);
        return responseEntity;
      }
      if (passengerId == null || passengerId == 0) {
        Error error = new Error(-20, "参数错误:客户不存在");
        responseEntity = new ResponseEntity<Object>(error, HttpStatus.OK);
        return responseEntity;
      }
      if (!PhoneNumberHelper.isPhoneNumber(passengerPhone)) {
        Error error = new Error(-1, "参数错误:电话号码格式不正确");
        responseEntity = new ResponseEntity<Object>(error, HttpStatus.OK);
        return responseEntity;
      }
      
      Passenger passenger = passengerApi.findById(passengerId, appKey);
      //并行单量判断
      Long count = errandManager.countNotFinishedByPassenger(passengerId,appKey);
      Long number=1L;
      if(null!=passenger.getPassengerGrade() && passenger.getPassengerGrade().getParallelOrderNumber() > 0 && count+number>passenger.getPassengerGrade().getParallelOrderNumber()){
        Error error = new Error(-86, "您当前有"+count+"个订单未结束!不能再下新单。");
        responseEntity = new ResponseEntity<Object>(error, HttpStatus.OK);
        return responseEntity;
      }
      
      JSONObject object = daijiaApi.getServices(wxApplication.getAddress());
      if (object != null) {
        Long num = 0L;
        boolean daijia = object.getBooleanValue("daijia");
        if (daijia) {
          num += daijiaApi.countNotPayAmounts(wxApplication.getAddress(), passengerId);
        }
        boolean zhuanche = object.getBooleanValue("zhuanche");
        if (zhuanche) {
          num += zhuanApi.countNotPayAmounts(passengerId, appKey);
        }
        boolean paotui = object.getBooleanValue("paotui");
        if (paotui) {
          num += errandManager.countNotPayAmounts(passengerId, appKey);
        }
        boolean freight = object.getBooleanValue("freight");
        if (freight) {
          num += freightManager.countNotPayAmounts(passengerId, appKey);
        }
        boolean zhuanxian = object.getBooleanValue("zhuanxian");
        if (zhuanxian) {
          num += zhuanXianApi.countNotPayAmounts(passengerId, appKey);
        }
        if (num > 0) {
          Error error = new Error(-54, "还有未完成支付的订单，不能下单");
          responseEntity = new ResponseEntity<Object>(error, HttpStatus.OK);
          return responseEntity;
        }
      }
      
//      Long countRunning = errandManager.countRunning(passengerId, appKey);
//      if (countRunning > 10) {
//        Error error = new Error(-55, "您今日下单已达到上限，继续下单请联系客服");
//        responseEntity = new ResponseEntity<Object>(error, HttpStatus.OK);
//        return responseEntity;
//      }

      Date startDate = null;
      if (null != startTime) {
        startDate = new Date(startTime);// 开始时间
      }else{
    	  startDate = new Date(); 
      }
      Order order =
          errandManager.saveOrder(passengerId, passengerName, passengerPhone, companyId,
              companyName, startAddress, startLat, startLng, deliverAddress, deliverLat,
              deliverLng, channelName, startDate, startPrice, mileagePrice, travelTimePrice,
              mileage, travelTime, shouldPay, orderTypeId, couponId, content, null, null, null,
              null, null, null, appKey,startDetailed,endDetailed,recipients,phone,weight,buyNeeds,goodsCash,thanksCash,addServices,tips,matter,false,null,null);
      String basePath =
          req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
              + req.getContextPath();
      String address = wxApplication.getAddress();
      String imgs = "";
      if (photo1 != null) {
        String photo1Url = CommonUtil.uploadErrandImg(photo1, req);
        String img = daijiaApi.uploadImg(address, order.getId(), basePath + "/" + photo1Url);
        imgs = img;
      }
      if (photo2 != null) {
        String photo2Url = CommonUtil.uploadErrandImg(photo2, req);
        String img = daijiaApi.uploadImg(address, order.getId(), basePath + "/" + photo2Url);
        imgs += "," + img;
      }
      if (photo3 != null) {
        String photo3Url = CommonUtil.uploadErrandImg(photo3, req);
        String img = daijiaApi.uploadImg(address, order.getId(), basePath + "/" + photo3Url);
        imgs += "," + img;
      }
      if (photo4 != null) {
        String photo4Url = CommonUtil.uploadErrandImg(photo4, req);
        String img = daijiaApi.uploadImg(address, order.getId(), basePath + "/" + photo4Url);
        imgs += "," + img;
      }
      if (photo5 != null) {
        String photo5Url = CommonUtil.uploadErrandImg(photo5, req);
        String img = daijiaApi.uploadImg(address, order.getId(), basePath + "/" + photo5Url);
        imgs += "," + img;
      }
      if (StringUtils.isNotBlank(imgs)) {
        errandManager.saveOrderImgs(order.getId(), channelName, imgs, appKey);
      }
      if (null != order.getId()) {
        daijiaApi.pushNewOrder(address, order.getId());
      }
      OrderType orderType = errandManager.findOrderType(orderTypeId, appKey);
      Map<String, Object> orderMap = errandManager.findOrderV2(order.getId(), appKey, wxApplication.getAddress());
      
      orderMap.put("errandValuationMethod", orderType.getErrandValuationMethod());
      Result<Map<String, Object>> result = new Result<Map<String, Object>>(0, "成功", orderMap);
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.CREATED);

      return responseEntity;

    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(-4, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }
  
  /**
   * 补单.
   */
  @ResponseBody
  @RequestMapping(value = {"createMore"}, method = RequestMethod.POST)
  public ResponseEntity<Object> createMore(
      @RequestParam("passengerPhone") String passengerPhone, 
      @RequestParam(required = false, value = "name") String name, 
      @RequestParam("employId") Long employId,
      @RequestParam("startAddress") String startAddress,
      @RequestParam("startLat") Double startLat,
      @RequestParam("startLng") Double startLng,
      @RequestParam("content") String content,
      @RequestParam("orderTypeId") Long orderTypeId, 
      @RequestParam(required = false, value = "deliverAddress") String deliverAddress,
      @RequestParam(required = false, value = "deliverLat") Double deliverLat,
      @RequestParam(required = false, value = "deliverLng") Double deliverLng, 
      HttpServletRequest req,
      @RequestParam("appKey") String appKey) {
    ResponseEntity<Object> responseEntity = null;
    try {
      appKey = StringUtils.trimToEmpty(appKey);
      Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
      WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
      if (StringUtils.isBlank(content)) {
        Error error = new Error(-1, "参数错误:任务内容为空");
        System.err.println("参数错误:任务内容为空");
        responseEntity = new ResponseEntity<Object>(error, HttpStatus.OK);
        return responseEntity;
      }
      if (StringUtils.isNotBlank(content) && content.length() > 200) {
        Error error = new Error(-41, "内容长度过长");
        System.err.println("内容长度过长");
        responseEntity = new ResponseEntity<Object>(error, HttpStatus.OK);
        return responseEntity;
      }
      boolean status = daijiaApi.findEmployStatus(wxApplication.getAddress(), employId);
      if (!status) {
        Error error = new Error(-21, "司机状态错误,不能补单");
        System.err.println("司机状态错误,不能补单");
        responseEntity = new ResponseEntity<Object>(error, HttpStatus.OK);
        return responseEntity;
      }
      Map<String, Object> driver = daijiaApi.queryDriver(wxApplication.getAddress(), employId);
      if ((int) driver.get("status") == 0) {
        Error error = new Error(-21, "司机未上班");
        System.err.println("司机未上班,不能补单");
        responseEntity = new ResponseEntity<Object>(error, HttpStatus.OK);
        return responseEntity;
      }


      Long employCompanyId = (Long) driver.get("employCompanyId");
      String employCompanyName = (String) driver.get("employCompanyName");
      if (null == employCompanyId || StringUtils.isBlank(employCompanyName)) {
        Error error = new Error(-1, "参数错误:公司不能为空");
        System.err.println("参数错误:公司不能为空");
        responseEntity = new ResponseEntity<Object>(error, HttpStatus.OK);
        return responseEntity;
      }
      if (!PhoneNumberHelper.isPhoneNumber(passengerPhone)) {
        Error error = new Error(-1, "参数错误:电话号码格式不正确");
        System.err.println("参数错误:电话号码格式不正确");
        responseEntity = new ResponseEntity<Object>(error, HttpStatus.OK);
        return responseEntity;
      }
      Passenger passenger = passengerApi.findOne(passengerPhone, appKey);
      final String employName = (String) driver.get("employName");
      final String employPhone = (String) driver.get("employPhone");
      if (passenger == null) {
        passenger =
            passengerApi.createPassenger(passengerPhone, name, employCompanyId, employCompanyName,
                "司机补单", appKey);
        if (passenger != null && passenger.getId() != null) {
          daijiaApi.newPassengerActivity(wxApplication.getAddress(), passenger.getId());
        }
      }
      if (null == passenger) {
        Error error = new Error(-20, "客户不存在");
        System.err.println("客户不存在");
        responseEntity = new ResponseEntity<Object>(error, HttpStatus.OK);
        return responseEntity;
      }
      Long couponId = null;
      try {
        List<Coupon> coupons = salesApi.findByPassengerId(passenger.getId(), "paotui", appKey);
        if (coupons != null && coupons.size() != 0) {
          couponId = coupons.get(0).getId();
        }
      } catch (Exception ex) {
        System.err.println("查询优惠券失败");
      }

      Long areaId = null;
      OrderType orderType = errandManager.findOrderType(orderTypeId, appKey);
      areaId = orderType != null ? orderType.getAreaId() : null;
      Double shouldPay = 0.0;
      Double mileage = 0.0;
      Integer travelTime = 0;
      Map<String, Object> map = daijiaApi.getPriceByAreaId(
              wxApplication.getAddress(), areaId, startLat, startLng, deliverLat, deliverLng);
      shouldPay = (Double) map.get("money");
      Double startPrice = 0.0;
      mileage = (Double) map.get("mileage");
      travelTime = (Integer) map.get("travelTime");
      startPrice = (Double) map.get("startPrice");
      Double mileagePrice = 0.0;
      Double travelTimePrice = 0.0;
      mileagePrice = (Double) map.get("mileagePrice");
      travelTimePrice = (Double) map.get("travelTimePrice");
      Date startDate = new Date(new Date().getTime() + 1000 * 10);// 开始时间

      Order order =
          errandManager.saveOrder(passenger.getId(), passenger.getName(), passenger.getPhone(),
              employCompanyId, employCompanyName, startAddress, startLat, startLng, deliverAddress,
              deliverLat, deliverLng, "司机补单", startDate, startPrice, mileagePrice, travelTimePrice,
              mileage, travelTime, shouldPay, orderTypeId, couponId, content, null, null, employId,
              employCompanyId, employName, employPhone, appKey,null,null,null,null,null,null,null,null,null,null,null,false,null,null);
      if (null != order) {
        daijiaApi.pushAcceptOrder(wxApplication.getAddress(), order.getId());
        Map<String, Object> orderMap =
            errandManager.findOrderV2(order.getId(), appKey, wxApplication.getAddress());
        orderMap.put("errandValuationMethod", orderType.getErrandValuationMethod());
        Result<Map<String, Object>> result = new Result<Map<String, Object>>(0, "成功", orderMap);
        responseEntity = new ResponseEntity<Object>(result, HttpStatus.CREATED);
      }
      return responseEntity;

    } catch (Exception ex) {
      logger.error(ex.getMessage());
      Error error = new Error(-4, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }

  /**
   * 查询单个跑腿订单.
   */
  @RequestMapping(value = {"findOne"}, method = RequestMethod.GET)
  public @ResponseBody Map<String, Object> findOne(
      @RequestParam("orderId") Long orderId,
      @RequestParam("appKey") String appKey) {

    Map<String, Object> map = new HashMap<String, Object>();
    appKey = StringUtils.trimToEmpty(appKey);

    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    try {
      Map<String, Object> order =
          errandManager.findOrderV2(orderId, appKey, wxApplication.getAddress());
      map.put("code", 0);
      map.put("msg", "成功");
      map.put("data", order);
      return map;
    } catch (Exception ex) {
      logger.error(ex.getMessage());
      map.put("code", -4);
      map.put("msg", ex.getMessage());
      return map;
    }
  }

  /**
   * 根据乘客Id,查询订单接口.
   */
  @RequestMapping(value = {"findOrder"}, method = RequestMethod.GET)
  public @ResponseBody Map<String, Object> findOrders(
      @RequestParam("passengerId") Long passengerId,
      @RequestParam("page") Integer page,
      @RequestParam("rows") Integer rows,
      @RequestParam("appKey") String appKey) {
    Map<String, Object> map = new HashMap<String, Object>();
    appKey = StringUtils.trimToEmpty(appKey);
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    try {
      DataGrid<Map<String, Object>> list = new DataGrid<Map<String, Object>>();
      list = errandManager.findOrderV2(passengerId, page, rows, appKey, wxApplication.getAddress());

      map.put("code", 0);
      map.put("msg", "成功");
      map.put("data", list);
      return map;
    } catch (Exception ex) {
      logger.error(ex.getMessage());
      map.put("code", -4);
      map.put("msg", "加载数据失败");
      return map;
    }
  }

  /**
   * v2评价订单.
   */
  @RequestMapping(value = {"review"}, method = RequestMethod.POST)
  public @ResponseBody Map<String, Object> review(
      @RequestParam("orderId") Long orderId,
      @RequestParam("score") Double score,
      @RequestParam("content") String content,
      @RequestParam("appKey") String appKey) {
    Map<String, Object> map = new HashMap<String, Object>();
    appKey = StringUtils.trimToEmpty(appKey);
    try {
      String result = errandManager.reviewV2(orderId, score, content, appKey);

      if (StringUtils.isBlank(result)) {
        map.put("code", 0);
        map.put("msg", "评价成功");
      } else {
        map.put("code", -1);
        map.put("msg", "评价失败");
      }
      return map;
    } catch (Exception ex) {
      logger.error(ex.getMessage());
      map.put("code", -4);
      map.put("msg", "评价失败");
      return map;
    }
  }

  /**
   * 修改订单状态.
   * @param orderId 订单ID
   * @param employId 司机(员工)ID
   * @param employName 司机名字
   * @param action 接单:"jiedan",执行:"run",销单:"cancel",拒单:"refuse"
   * @param operator 操作人
   * @param cause 销单原因
   * @param appKey 区分系统
   */
  @RequestMapping(value = {"updateStatus"}, method = RequestMethod.POST)
  public @ResponseBody Map<String, Object> updateStatus(
      @RequestParam("orderId") Long orderId,
      @RequestParam(required = false, value = "employId") Long employId,
      @RequestParam(required = false, value = "employName") String employName, 
      @RequestParam(required = false, value = "employPhone") String employPhone,
      @RequestParam(required = false, value = "employCompanyId") Long employCompanyId,
      @RequestParam("action") String action, 
      @RequestParam("operator") String operator,
      @RequestParam(required = false, value = "cause") String cause,
      @RequestParam("appKey") String appKey) {
    Map<String, Object> map = new HashMap<String, Object>();
    appKey = StringUtils.trimToEmpty(appKey);
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    try {
      Order order = errandManager.findOneOrderV2(orderId, appKey);
      if (order == null) {
        map.put("code", -9);
        map.put("msg", "订单不存在!");
        return map;
      } else if ("cancel".equals(action) && order.getStatus() > 0) {
        map.put("code", -10);
        map.put("msg", "订单已开始执行,不能销单!");
        return map;
      } else if ("jiedan".equals(action)) {
        boolean bool = false;
        bool = daijiaApi.findEmployStatus(wxApplication.getAddress(), employId);
        if (!bool) {
          map.put("code", -21);
          map.put("msg", "司机忙碌,暂时不能接单");
          return map;
        }
      }
      if ("cancel".equals(action)) {
        employId = order.getEmployId();
      }
      String result =
          errandManager.updateStatusV2(orderId, employId, employName, employPhone, employCompanyId,
              action, operator, cause, appKey);
      if (StringUtils.isBlank(result)) {
        map.put("code", 0);
        map.put("msg", "成功");
      } else {
        System.err.println(result);
        map.put("code", -1);
        map.put("msg", "操作失败");
      }
      return map;
    } catch (HttpClientErrorException ex) {
      logger.error(ex.getMessage());
      map.put("code", -4);
      map.put("msg", "操作失败");
      return map;
    } catch (HttpServerErrorException ex) {
      logger.error(ex.getMessage());
      map.put("code", -4);
      map.put("msg", "操作失败");
      return map;
    } catch (Exception ex) {
      logger.error(ex.getMessage());
      map.put("code", -4);
      map.put("msg", "操作失败");
      return map;
    }
  }

  /**
   * V2抢单.
   */
  @RequestMapping(value = "grab", method = RequestMethod.GET)
  public @ResponseBody Map<String, Object> grabOrder(@RequestParam("orderId") Long orderId,
      @RequestParam("employId") Long employId, @RequestParam("employName") String employName,
      @RequestParam("employPhone") String employPhone,
      @RequestParam("employCompanyId") Long employCompanyId,
      @RequestParam("distance") Double distance, @RequestParam("appKey") String appKey) {
    Map<String, Object> map = new HashMap<String, Object>();
    map =
        errandManager.grabV2(employName, employPhone, distance, orderId, employId, employCompanyId,
            appKey);
    return map;
  }

  /**
   * 催一下订单进度.
   */
  @RequestMapping(value = {"reminder"}, method = RequestMethod.GET)
  public @ResponseBody Map<String, Object> reminder(@RequestParam("orderId") Long orderId,
      @RequestParam("appKey") String appKey) throws Exception {
    Map<String, Object> map = new HashMap<String, Object>();

    appKey = StringUtils.trimToEmpty(appKey);
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);

    Order order = errandManager.findOneOrderV2(orderId, appKey);
    if (null == order) {
      map.put("code", -1);
      map.put("msg", "订单不存在");
      return map;
    }
    if (order.getStatus() == 4 || order.getStatus() == 5) {
      map.put("code", -1);
      map.put("msg", "订单已完成,或已销单,催促无效");
      return map;
    }
    if (order.getLasturge() != null) {
      if ((new Date().getTime() - order.getLasturge().getTime()) < (2 * 60 * 1000)) {
        map.put("code", -1);
        if (order.getCreated().getTime() == order.getLasturge().getTime()) {
          map.put("msg", "我们正在为您寻找服务人员");
        } else {
          map.put("msg", "订单刚催促过,两分钟内不能重复操作");
        }
        return map;
      }
    }

    try {

      daijiaApi.hastenOrder(wxApplication.getAddress(), orderId); // 调用代驾的接口让其显示消息

      String content = errandManager.hastenV2(orderId, appKey); // 调用跑腿系统更新上次催促时间
      if ("success".equals(content)) {
        map.put("code", 0);
        map.put("msg", "消息已发出,管理员已经知道了");
      } else if ("fail".equals(content)) {
        map.put("code", -4);
        map.put("msg", "操作失败");
      }
      return map;
    } catch (Exception ex) {
      logger.error(ex.getMessage());
      map.put("code", -4);
      map.put("msg", "催促操作失败");
      return map;
    }
  }
  
  /**
   * 查询服务人员执行中的订单.
   */
  @RequestMapping(value = {"findMyWork"}, method = RequestMethod.GET)
  public @ResponseBody Map<String, Object> findMyWork(
      @RequestParam("employId") Long employId,
      @RequestParam(required = false, value = "longitude") Double longitude, 
      @RequestParam(required = false, value = "latitude") Double latitude,
      @RequestParam("page") Integer page, 
      @RequestParam("rows") Integer rows,
      @RequestParam("appKey") String appKey) {
    Map<String, Object> map = new HashMap<String, Object>();
    appKey = StringUtils.trimToEmpty(appKey);
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    try {
      DataGrid<Map<String, Object>> dataGrid = new DataGrid<Map<String, Object>>();
      dataGrid = errandManager.findMyWorkV2(
          employId, longitude, latitude, page, rows, appKey, wxApplication.getAddress());
      map.put("code", 0);
      map.put("msg", "成功");
      map.put("data", dataGrid);
      return map;
    } catch (Exception ex) {
      logger.error(ex.getMessage());
      map.put("code", -4);
      map.put("msg", "加载数据失败");
      return map;
    }
  }
  /**
   * 分页查询服务人员完成的订单.
   */
  
  @RequestMapping(value = {"queryFinishOrder"}, method = RequestMethod.GET)
  public @ResponseBody Map<String, Object> queryFinishOrder(
      @RequestParam("employId") Long employId,
      @RequestParam("page") Integer page,
      @RequestParam("rows") Integer rows, 
      @RequestParam("appKey") String appKey) {
    Map<String, Object> map = new HashMap<String, Object>();
    appKey = StringUtils.trimToEmpty(appKey);
    try {
      DataGrid<Map<String, Object>> dataGrid = new DataGrid<Map<String, Object>>();
      dataGrid = errandManager.queryFinishOrderV2(employId, page, rows, appKey);
      map.put("code", 0);
      map.put("msg", "成功");
      map.put("data", dataGrid);
      return map;
    } catch (Exception ex) {
      logger.error(ex.getMessage());
      map.put("code", -4);
      map.put("msg", "加载数据失败");
      return map;
    }
  }

  /**
   * 跑腿订单客户端支付所需数据.
   */
  @RequestMapping(value = {"clientPayData"}, method = RequestMethod.GET)
  public @ResponseBody Map<String, Object> clientPayData(
      @RequestParam("orderId") Long orderId,
      @RequestParam("appKey") String appKey) {
    Map<String, Object> map = new HashMap<String, Object>();
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    try {
      map = daijiaApi.clientPayDataErrand(wxApplication.getAddress(), orderId);
      return map;
    } catch (Exception ex) {
      logger.error(ex.getMessage());
      map.put("code", -4);
      map.put("msg", "获取跑腿结算页面的数据失败");
      return map;
    }
  }

  /**
   * 客户端支付宝结算跑腿订单.
   */
  @RequestMapping(value = {"aliAfterPay"}, method = RequestMethod.GET)
  public @ResponseBody Map<String, Object> aliAfterpay(
      @RequestParam("orderId") Long orderId,
      @RequestParam("appKey") String appKey) {
    Map<String, Object> map = new HashMap<String, Object>();
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    try {
      map = daijiaApi.aliAfterpayErrand(wxApplication.getAddress(), orderId);
      return map;
    } catch (Exception ex) {
      logger.error(ex.getMessage());
      map.put("code", -4);
      map.put("msg", "内部服务器错误");
      return map;
    }
  }

  /**
   * 客户端微信结算跑腿订单.
   */
  @RequestMapping(value = {"wxAfterPay"}, method = RequestMethod.GET)
  public @ResponseBody Map<String, Object> wxAfterpay(
      @RequestParam("orderId") Long orderId,
      @RequestParam("appKey") String appKey) {
    Map<String, Object> map = new HashMap<String, Object>();
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    try {
      map = daijiaApi.wxAfterpayErrand(wxApplication.getAddress(), orderId);
      return map;
    } catch (Exception ex) {
      logger.error(ex.getMessage());
      map.put("code", -4);
      map.put("msg", "获取结算页面的数据失败");
      return map;
    }
  }

  /**
   * 跑腿订单结算页面的数据.
   */
  @RequestMapping(value = {"completeTask"}, method = RequestMethod.GET)
  public @ResponseBody Map<String, Object> completeTask(
      @RequestParam("orderId") Long orderId,
      @RequestParam("appKey") String appKey) {
    Map<String, Object> map = new HashMap<String, Object>();
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    try {
      map = daijiaApi.completeTaskErrand(wxApplication.getAddress(), orderId);
      return map;
    } catch (Exception ex) {
      logger.error(ex.getMessage());
      map.put("code", -4);
      map.put("msg", "获取跑腿结算页面的数据失败");
      return map;
    }
  }

  /**
   * 确认跑腿订单费用的接口.
   * @param orderId 订单id
   * @param realCash 实付金额
   * @param mileage 行驶里程
   * @param waitedTime 等侯时间
   * @param travelTime 执行时间
   * @param startPrice 起步价
   * @param mileagePrice 里程费用
   * @param runTimePrice 时间费用
   * @param waitPrice 等候时间
   * @param memo 备注
   */
  @RequestMapping(value = {"confirmTask"}, method = RequestMethod.POST)
  public @ResponseBody Map<String, Object> confirmTask(
      @RequestParam("orderId") Long orderId,
      @RequestParam("realCash") Double realCash,
      @RequestParam("guoluMoney") Double guoluMoney,
      @RequestParam("yuanchengMoney") Double yuanchengMoney,
      @RequestParam("otherMoney") Double otherMoney,
      @RequestParam("mileage") Double mileage,
      @RequestParam("waitedTime") Integer waitedTime,
      @RequestParam("travelTime") Integer travelTime,
      @RequestParam("startPrice") Double startPrice,
      @RequestParam("mileagePrice") Double mileagePrice,
      @RequestParam("runTimePrice") Double runTimePrice,
      @RequestParam("waitPrice") Double waitPrice,
      @RequestParam(required = false, value = "memo") String memo, 
      @RequestParam("xml") String xml,
      @RequestParam("appKey") String appKey) {
    Map<String, Object> map = new HashMap<String, Object>();
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    try {
      Order order = errandManager.findOneOrderV2(orderId, appKey);
      if (order.getStatus() == 5) {
        map.put("code", -10);
        map.put("msg", "订单已经取消");
        return map;
      }
      map =
          daijiaApi.confirmTaskErrand(wxApplication.getAddress(), orderId, realCash, guoluMoney,
              yuanchengMoney, otherMoney, mileage, waitedTime, travelTime, startPrice,
              mileagePrice, runTimePrice, waitPrice, memo, xml);
      return map;
    } catch (Exception ex) {
      logger.error(ex.getMessage());
      map.put("code", -4);
      map.put("msg", "内部服务器错误");
      return map;
    }
  }

  /**
   * 实时获取订单是否被结算.
   */
  @RequestMapping(value = {"checkTask"}, method = RequestMethod.GET)
  public @ResponseBody Map<String, Object> checkTask(
      @RequestParam("orderId") Long orderId,
      @RequestParam("appKey") String appKey) {
    Map<String, Object> map = new HashMap<String, Object>();
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    try {
      map = daijiaApi.checkTaskErrand(wxApplication.getAddress(), orderId);
      return map;
    } catch (Exception ex) {
      logger.error(ex.getMessage());
      map.put("code", -4);
      map.put("msg", "实时获取订单是否被结算失败!");
      return map;
    }
  }

  /**
   * 最后结算接口.
   * @param payType 支付类型: helppay(代付) sign(签单) balance(余额)
   */
  @ResponseBody
  @RequestMapping(value = {"finishTask"}, method = RequestMethod.GET)
  public Map<String, Object> finishTask(
      @RequestParam("orderId") Long orderId,
      @RequestParam("payType") String payType,
      @RequestParam(required = false, value = "who") String who,
      @RequestParam("appKey") String appKey) {
    Map<String, Object> map = new HashMap<String, Object>();
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    try {
      map = daijiaApi.finishTaskErrand(wxApplication.getAddress(), orderId, payType, who);
      return map;
    } catch (Exception ex) {
      logger.error(ex.getMessage());
      map.put("code", -4);
      map.put("msg", "结算提交失败!");
      return map;
    }
  }

}
